package com.baomidou.wechat.mp.apistore.actuator;

import java.util.Map;

import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;

import com.baomidou.wechat.api.WechatAPISupport;
import com.baomidou.wechat.common.util.HttpUtil;

/**
 * api 执行器
 */
public abstract class ApiStoreActuator<T> extends WechatAPISupport {

	protected static final String API_STORE = "http://apis.baidu.com/";
	protected static final String API_STORE_APIKEY = "4423a2ea4332ef21b1380fae03e0c688";

	public abstract T execute();

	/**
	 * 重写组合请求地址
	 */
	protected String mergeUrl(String url, Object... values) {
		StringBuffer uri = new StringBuffer(API_STORE);
		if (values != null) {
			uri.append(String.format(url, values));
		}
		return uri.toString();
	}

	protected String executeHttpGet(Map<String, String> data, String url, Object... values) {
		return executeHttp(Method.GET, data, url, values);
	}

	protected String executeHttpPost(Map<String, String> data, String url, Object... values) {
		return executeHttp(Method.POST, data, url, values);
	}

	private String executeHttp(Method method, Map<String, String> data, String url, Object... values) {
		try {
			Connection conn = HttpUtil.getConnection(mergeUrl(url, values));
			if (data != null) {
				conn.data(data);
			}
			Response resp = conn.header("apikey", API_STORE_APIKEY).method(method).execute();
			if (isOK(resp.statusCode())) {
				return resp.body();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
